#define SETTINGSTEP 6
// TCP 数据传输
#include "installprogram.h"
#include <QTcpServer>
#include <QProcess>

#include <QHostAddress>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QEventLoop>
#include <QTimer>
#include <QNetworkReply>
#include <QFile>
#include <QObject>
#include <QNetworkInterface>
#include <QTcpSocket>
//#include <QTemporaryDir>
#include <QDir>

installprogram::installprogram()
{
    // 启动服务
    Server();
}
// 获取程序
void installprogram::Server(){
    //lock = false;
        tcp = new QTcpServer();
        QHostAddress ip("0.0.0.0");
        tcp->listen(QHostAddress::Any, 56678);
        // 获取 IP 地址
        QString IpAddress;
        foreach (QHostAddress address, QNetworkInterface::allAddresses())
        {
            if(address.protocol() == QAbstractSocket::IPv4Protocol && address.toString() != "127.0.0.1" && address.toString() != "192.168.250.1"){
                IpAddress = address.toString();
            }
        }
        qDebug() << "服务器IP：" << IpAddress;
        qDebug() << "服务器端口：" << tcp->serverPort();
        //localIp->setText("访问：http://" + IpAddress + ":" + QString::number(tcp->serverPort()) + " 连接");
        connect(tcp, &QTcpServer::newConnection, this, [this](){
            qDebug() << "bb";
            tcpSocket = tcp->nextPendingConnection();
            QString ipAddress = QHostAddress(tcpSocket->peerAddress().toIPv4Address()).toString();
            qDebug() << ipAddress;
            qDebug() << tcpSocket->peerPort();
            //tcpSocket->write("HTTP/1.1 200 OK"\
//                             "Content-Type: text/html;charset=utf-8"\
//                             "\n\n");
            //tcpSocket->write(QString("<html><body><p>IP Address: " + ipAddress + "</p><p>Get Port: " + QString::number(tcpSocket->peerPort()) + "</p></body></html>").toLocal8Bit());
            // 下载文件
            //tcpSocket->write();
            tcpSocket->waitForBytesWritten();
            tcpSocket->waitForReadyRead();
            if (Download(shareUrl + tcpSocket->readAll(), QDir::tempPath() + "/install.exe", tcpSocket)){
                tcpSocket->write("OK");
                RunProgram(QDir::tempPath() + "/install.exe");
            }
            else{
                tcpSocket->write("Error");
            }

            tcpSocket->close();
        });
        qDebug() << "a";
}

// 下载程序
bool installprogram::Download(QString url, QString savePath, QTcpSocket *socket){
    // 文件下载
    int timeout = 0;
    QFile f(savePath);
    if(!f.open(QIODevice::WriteOnly)){
        f.close();
        return false;
    }
    QNetworkAccessManager m;
    QNetworkRequest req;
    // 响应 https（就是不行）
    QSslConfiguration conf = req.sslConfiguration();
    conf.setPeerVerifyMode(QSslSocket::VerifyNone);
    conf.setProtocol(QSsl::TlsV1_1);
    req.setSslConfiguration(conf);
    req.setUrl(QUrl(url));
    // 下载文件
    QNetworkReply *reply = m.get(req);
    QEventLoop loop;
    QTimer t;
    qDebug() << reply->rawHeader(QString("Content-Length").toUtf8());
    connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    connect(reply, &QNetworkReply::downloadProgress, [=, &f, &t](qint64 bytesRead, qint64 totalBytes){
        f.write(reply->readAll());
        socket->write(QString::number((float)bytesRead / totalBytes * 100).toUtf8());
        if(t.isActive()){
            t.start(timeout);
        }
    });
    if(timeout > 0){
        connect(&t, &QTimer::timeout, &loop, &QEventLoop::quit);
        t.start(timeout);
    }
    loop.exec();
    if(reply->error() != QNetworkReply::NoError){
        qDebug() << "b";
        f.close();
        delete reply;
        return false;
     }
    socket->write("");
    delete reply;
    return true;
}

// 运行程序
int installprogram::RunProgram(QString path){
    QProcess process;
    process.start(path);
    process.waitForFinished();
    int value = process.exitStatus();
    process.close();
    return value;
}
